//
//  SoundTouchWrapper.m
//  YHSoundTouch
//
//  Created by amovision on 2025/11/4.
//

#import "SoundTouchWrapper.h"
#import "SoundTouch.h"

@interface SoundTouchWrapper ()

@property (nonatomic, assign) soundtouch::SoundTouch *soundTouch;

@end

@implementation SoundTouchWrapper

- (void)setRate:(float)rate {
  _rate = rate;
  _soundTouch->setRate(rate);
}

- (void)setChannels:(unsigned int)channels {
  _channels = channels;
  _soundTouch->setChannels(channels);
}

- (void)setSampleRate:(unsigned int)sampleRate {
  _sampleRate = sampleRate;
  _soundTouch->setSampleRate(sampleRate);
}

- (void)setPitch:(float)pitch {
  _pitch = pitch;
  _soundTouch->setPitch(pitch);
}

- (void)setTempo:(float)tempo {
  _tempo = tempo;
  _soundTouch->setTempo(tempo);
}

- (void)setPitchSemiTones:(int)pitchSemiTones {
  _pitchSemiTones = pitchSemiTones;
  _soundTouch->setPitchSemiTones(pitchSemiTones);
}

- (instancetype)init
{
  self = [super init];
  if (self) {
    _soundTouch = new soundtouch::SoundTouch();
  }
  return self;
}

- (NSData *)putSamples:(NSData *)data {
  _soundTouch->putSamples((short *)data.bytes, (unsigned int)data.length / 2);
  NSMutableData *outData = [NSMutableData dataWithLength:1024];
  int numOfSamples = _soundTouch->receiveSamples((short *)outData.bytes, (unsigned int)data.length);
  return [outData subdataWithRange:NSMakeRange(0, numOfSamples*2)];
}

- (void)dealloc {
  delete _soundTouch;
}

@end
